package pl.squeaky.mvc.generator;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.runtime.CoreException;

public class ViewGenerator extends Generator {
	
	private String name;

	public ViewGenerator(String name) {
		this.name = name;
	}
	
	public static void setupViewsFolderStructure(IFolder viewsFolder, String controllerName) {
		if(viewsFolder != null) {
			IFolder scriptsFolder = null;
			IFolder controllerScriptsFolder = null;
			scriptsFolder = viewsFolder.getFolder("scripts");
			if(!scriptsFolder.exists()) {
				try {
					scriptsFolder.create(false, true, null);
				} catch (CoreException e) {
					throw new RuntimeException(e);
				}
			}
			
			String controllerScriptsFolderName = controllerName.toLowerCase(); 
			controllerScriptsFolder = scriptsFolder.getFolder(controllerScriptsFolderName);
			if(!controllerScriptsFolder.exists()) {
				try {
					controllerScriptsFolder.create(false, true, null);
				} catch(CoreException e) {
					throw new RuntimeException(e);
				}
			}
		}
	}
	
	public void generate(IFolder viewsFolder, String controllerName) {
		IFolder scriptsFolder = viewsFolder.getFolder("scripts");
		IFolder controllerViewFolder = scriptsFolder.getFolder(controllerName.toLowerCase());
		IFile file = controllerViewFolder.getFile(name + ".phtml");
		
		generate(file);
	}
	
	@Override
	public void generate(IFile file) {
		String content = "<h1>" + name + ".phtml</h1>\n<p>This is autogenerated content.</p>";
		
		save(file, content);
	}

}
